package com.nervenets.web.controller.handler.admin.user;

import com.nervenets.utils.JodaUtils;
import com.nervenets.web.controller.handler.SessionHandler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.enumeration.*;
import com.nervenets.web.hibernate.domain.user.User;
import com.nervenets.web.rabbitmq.FlowMessage;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

public class UserIdCheckHandler extends SessionHandler<UserIdCheckParams> {
    @Override
    public ArrayList<Role> allowRoles() {
        return Role.administrator();
    }

    @Override
    public boolean needLog() {
        return false;
    }

    @Override
    public String handle(UserIdCheckParams params, HttpServletRequest request) throws Exception {
        return (String) redisSyncLocker.idLock(params.getUserId(), o -> {
            final User user = userDao.findById(params.getTargetUserId(), User.class);
            if (null == user) return errorMessage(MessageCode.code_404, "用户不存在");

            if (!AuthStatus.checking.equals(user.getAuthStatus())) {
                return errorMessage(MessageCode.code_444, "该用户资料已审核，请不要重复点击");
            }

            if (params.isSuccess()) {
                user.setAuthTime(JodaUtils.getTimestamp());
                user.setAuthStatus(AuthStatus.success);
            } else {
                user.setAuthStatus(AuthStatus.failed);
                user.getInfo().setFailedReason(params.getFailedReason());
            }

            userDao.saveOrUpdate(user);
            globalService.clearRedisUserStored(user.getId());

            if (params.isSuccess()) {
                final long scoreOfIdAuth = globalVariablesService.getGlobalRule().getScoreOfIdAuth();
                if (scoreOfIdAuth > 0) {
                    messageProducer.flow(FlowMessage.scoreChange(params.getTargetUserId(), getIp(request), UnionType.normal, 0, scoreOfIdAuth, OperateType.idAuth, PayType.surplus, FlowStatus.success, "实名认证积分"));
                }
            }

            return successMessage();
        });
    }

    @Override
    public String result() throws Exception {
        return successMessage();
    }
}
